let wechatUserId = sessionStorage.getItem('userId');
let companyId = sessionStorage.getItem('companyId');
let deviceCode = sessionStorage.getItem('deviceCode');
let dataType = sessionStorage.getItem('selectDataType');
let codeDictCode = sessionStorage.getItem('codeDictCode');
let codeDictName = '';
let codeDictUnit = '';
let chart;
let chartOption;
let chart2;
let chartOption2;
let avgCount = 0;
let reallyAvgCount = 0;
let emissionName = '';
let emissionUnit = '';
let userModuleIdList = sessionStorage.getItem("userModuleIdList");

$(function () {
    if (null === wechatUserId || wechatUserId === '') {
        wechatUserId = sessionStorage.getItem('loginWeChatUserId');
    } else {
        sessionStorage.setItem('loginWeChatUserId', wechatUserId);
    }

    // 初始化图表
    chart = echarts.init(document.getElementById('mainChart'));
    chart2 = echarts.init(document.getElementById('mainChart2'));

    getDeviceInfo();
});

function getDeviceInfo() {
    $.post(serverUrl + ':' + serverPort + serverName + '/device/getInfoByCode', {
        code: deviceCode
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            let type = '';

            switch (Number(dataType)) {
                case 2011:
                    type = '实时数据';
                    break;
                case 2051:
                    type = '分钟数据';
                    break;
                case 2061:
                    type = '小时数据';
                    break;
                case 2031:
                    type = '日均数据';
                    break;
                default:
                    type = '未知数据';
                    break;
            }

            $('#chartTitle').html(obj.data.name + ' => ' + type);

            getCodeDictInfo();
        }
    });
}

function getCodeDictInfo() {
    $.post(serverUrl + ':' + serverPort + serverName + '/codeDict/getInfoByCode', {
        type: 'HJ212-2005', code: codeDictCode
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            if (typeof obj.data.name !== "undefined") {
                codeDictName = obj.data.name;
                codeDictUnit = obj.data.unit;

                $('#chartDesc').html(codeDictName + '（单位：' + codeDictUnit + '）');
            } else {
                codeDictName = codeDictCode;
                codeDictUnit = '';

                $('#chartDesc').html(codeDictName);
            }

            setTimeout(function () {
                loadDeviceData();
            }, 200);

            if (userModuleIdList.includes('@' + deviceOtherEmissionIndex + '@')) {
                setTimeout(function () {
                    loadDeviceData2();
                }, 400);
            }
        }
    });
}

function loadDeviceData() {
    showLoading();

    $.post(serverUrl + ':' + serverPort + serverName + '/data/iFindDataListByDeviceCodeAndTypeAndCodeDictCode', {
        deviceCode: deviceCode, type: dataType, codeDictCode: codeDictCode, count: 100
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            if (obj.data.length > 0) {
                loadTableData(obj.data);
            }
        }
    });
}

function loadTableData(data) {
    let xAxisData = [];
    let yAxisData = [];

    $.each(data, function (i, item) {
        const dataTime = changeStrTime(item['CP_DataTime']);

        if (dataTime !== '') {
            xAxisData.push(dataTime);
            yAxisData.push(item[codeDictCode]);
        }
    });

    chartOption = {
        title: {
            text: codeDictName + '_历史走向', left: 'center', top: 10, textStyle: {
                fontSize: 18, fontWeight: 'bold'
            }
        }, xAxis: {
            type: 'category', data: xAxisData
        }, yAxis: {
            type: 'value'
        }, series: [{
            data: yAxisData, type: 'line', smooth: true, areaStyle: {
                color: 'rgba(0,168,132,0.2)'
            }, lineStyle: {
                width: 2
            }
        }], tooltip: {
            trigger: 'axis', formatter: function (params) {
                return `时间：${params[0].name}<br/>数值：${params[0].value} ` + codeDictUnit;
            }
        }
    };

    chart.setOption(chartOption);

    // 窗口调整时自适应
    window.addEventListener('resize', () => chart.resize());
}

function loadDeviceData2() {
    showLoading();

    $.post(serverUrl + ':' + serverPort + serverName + '/deviceSummary/iFindListWithEmission', {
        deviceCode: deviceCode, codeDictCode: codeDictCode, count: 10
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            if (obj.data.valueList.length > 0) {
                emissionName = obj.data.codeDictName;
                emissionUnit = obj.data.codeDictUnit;
                avgCount = obj.data.emissionAvg;
                reallyAvgCount = avgCount;
                loadTableData2(obj.data.valueList);
            }
        }
    });
}

function loadTableData2(data) {
    let xAxisData = [];
    let yAxisData = [];

    $.each(data, function (i, item) {
        const dataTime = changeStrTime(item['name']);

        if (dataTime !== '') {
            xAxisData.push(dataTime);
            yAxisData.push(item['count']);

            // 轮询检测是否超过限值
            if (Number(item['count']) >= avgCount) {
                reallyAvgCount = Number(item['count']);
            }
        }
    });

    chartOption2 = {
        title: {
            text: emissionName.replace('排放量', '').replace('累计', '') + '_近十日排放量统计', left: 'center', top: 10, textStyle: {
                fontSize: 18, fontWeight: 'bold'
            }
        }, xAxis: {
            type: 'category', data: xAxisData
        }, yAxis: {
            type: 'value',
            max: reallyAvgCount,
            min: 0
        }, series: [{
            data: yAxisData, type: 'bar', itemStyle: {
                color: '#5470c6'
            }, markLine: {
                symbol: 'none', z: 9999, lineStyle: {
                    type: 'dashed', color: '#ff6b6b', width: 2
                }, label: {
                    formatter: '平均值: {c}' + emissionUnit, position: 'middle'
                }, data: [{
                    yAxis: (reallyAvgCount > avgCount ? avgCount : reallyAvgCount), name: '平均值'
                }]
            }
        }], tooltip: {
            trigger: 'axis', formatter: function (params) {
                return `时间：${params[0].name}<br/>数值：${params[0].value} ` + emissionUnit;
            }
        }
    };

    chart2.setOption(chartOption2);

    // 窗口调整时自适应
    window.addEventListener('resize', () => chart2.resize());
}